extends NodeState


@export var player: Player


var velocity: Vector2 = Vector2.ZERO
var height: float = 0.0
var height_speed: float = 0.0


func _on_process(delta : float) -> void:
	player.position += velocity * delta
	process_air_time(delta)



func _on_enter() -> void:
	player.enabled = false
	height = 0.0
	player.collisionShape.set_deferred("disabled", true)
	# 进入死亡时不允许再接收伤害
	player.damageReceiver.set_deferred("monitorable", false)

	process_animation()
	process_affected()

	player.enemySlots.all_slots_disabled(true)
	player.enemySlots.free_all_slots()
	StageManager.player_death()


func _on_exit() -> void:
	player.enabled = true
	player.collisionShape.set_deferred("disabled", false)
	player.damageReceiver.set_deferred("monitorable", true)



func process_animation():
	player.animationPlayer.play(Player.ANIMATION_DEATH)


# 受到攻击时的效果
func process_affected():
	var emit_direction := player.take_damage_emit_direction()
	if emit_direction == null:
		return

	var direction: Vector2 = Vector2.RIGHT if emit_direction.x > 0 else Vector2.LEFT
	player.look_at_direction(direction * -1)

	velocity = direction * player.knockback_intensity
	height_speed = player.knockdown_intensity


func process_air_time(delta: float):
	player.characterSprite.position = Vector2.UP * height

	height += height_speed * delta
	# 高度降为0时进入倒地状态
	if height < 0.0:
		height = 0.0
		velocity = Vector2.ZERO
	else:
		height_speed -= player.gravity * delta


# 动画结束
func on_death_animation_finished():
	pass
